package com.tanjun.web.config;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tanjun.common.exception.BizException;
import com.tanjun.common.model.R;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Feign调用的时候返回结果统一处理，将返回结果为R.error的统一改为抛异常
 */
@Slf4j
@Configuration
public class ResultFeignDecoder implements Decoder {
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 返回结果反序列化
     * @param response
     * @param type
     * @return
     * @throws IOException
     * @throws DecodeException
     * @throws FeignException
     */
    @Override
    public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
        log.info("请求参数:{},返回结果:{}",response.request().url(),response.body().toString());
        String bodyString = Util.toString(response.body().asReader(Util.UTF_8));
        JavaType parameterType = objectMapper.getTypeFactory().constructType(type);
        R<?> result = objectMapper.readValue(bodyString, parameterType);
        // 如果响应状态为失败，抛出业务异常
        if (!result.isSuccess()) {
            throw new BizException(result.getMsg());
        }
        return result;
    }
}
